#include "T_CustomRectItem.h"
#include <QPainter>
#include <QCursor>
#include <QDebug>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMenu>
#include "marsspace.h"
#include "crectandpos.h"
#include "ElaWidget.h"
#include "ElaComboBox.h"
#include "ElaMultiSelectComboBox.h"
#include "ElaText.h"
#include "ElaPushButton.h"
#include "ElaLineEdit.h"
#include "ElaMessageBar.h"

T_CustomRectItem::T_CustomRectItem(QObject *parent)
{
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setAcceptHoverEvents(true);
}

T_CustomRectItem::~T_CustomRectItem()
{
   
}

void T_CustomRectItem::SetItemInfo(cutomitem data)
{
    QString tmp_name = data.name.split("_").first();
    
    int num = 1;
    for(auto name : g_item_names) {
        if(name.contains(tmp_name)) {
            num += 1;
        }
    }

    if(data.type == Block){
        data.name = "";
    } else {
        data.name = QString("%1_%2").arg(tmp_name).arg(num);
    }
    g_item_names.append(data.name);   
    m_item_data = data;

    QColor brush_color(data.color);
    brush_color.setAlpha(120);
    setBrush(brush_color);
    setRect(data.rect);

    if(data.type == rectType::Main)
    {
        setZValue(-3);
    } else if(data.type == rectType::Outer) {
        setZValue(-2);
    } else if(data.type == rectType::Module) {
        setZValue(-1);
    } else if(data.type == rectType::Block)  {
        setZValue(0);
    }
}

void T_CustomRectItem::addChild(QGraphicsRectItem *child)
{
    if (child && !m_children.contains(child)) {
        m_children.append(child);
        child->setParentItem(this);
    }
}

void T_CustomRectItem::removeChild(QGraphicsRectItem *child)
{
    if (m_children.removeOne(child)) {
        child->setParentItem(nullptr);
    }
}

void T_CustomRectItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    return;

    if((event->buttons() & Qt::LeftButton) == 0){
        return;
    }
    m_is_tip = true;

    // qDebug() << "view pos: " << scene()->views().first()->mapFromScene(event->scenePos());
    // qDebug() << "scene pos: " << event->scenePos();
    // qDebug() << "item pos: " << mapFromScene(event->scenePos());
    // qDebug() << "pos: " << event->pos();
    // qDebug() << "\n";
    // qDebug() << "type: " << m_item_data.type;
    if(m_resizeDirection == Inner) {
        //刷新当前显示的数据
        m_isCopying = event->modifiers() & Qt::ControlModifier;
        if(m_isCopying) {
            m_mousePressPos = event->scenePos();
            // qDebug() << " press scene: " << event->scenePos();
        }
    }

    m_resizing = (m_resizeDirection != None && m_resizeDirection != Inner);
    m_lastMousePos = event->pos();
    m_lastPos = pos();

    if (m_resizing) {
        calaOldRects();
    }
    else{
        QGraphicsRectItem::mousePressEvent(event);
    }
}

void T_CustomRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    return;

    //qDebug() << "move: " << event->buttons();
    if((event->buttons() & Qt::LeftButton) == 0){
        return;
    }
    m_is_tip = false;
    // if(m_resizing)
    // {
    //     QPointF delta = event->pos() - m_lastMousePos;
    //     QRectF newRect = rect();

    //     switch (m_resizeDirection)
    //     {
    //     case Left: newRect.setLeft(newRect.left() + delta.x()); break;
    //     case Right: newRect.setRight(newRect.right() + delta.x()); break;
    //     case Top: newRect.setTop(newRect.top() + delta.y()); break;
    //     case Bottom: newRect.setBottom(newRect.bottom() + delta.y()); break;
    //     case TopLeft: newRect.setTopLeft(newRect.topLeft() + delta); break;
    //     case TopRight: newRect.setTopRight(newRect.topRight() + delta); break;
    //     case BottomLeft: newRect.setBottomLeft(newRect.bottomLeft() + delta); break;
    //     case BottomRight: newRect.setBottomRight(newRect.bottomRight() + delta); break;
    //     default: break;
    //     }
    //     calcZoomRects(newRect);

    //     m_lastMousePos = event->pos();
    // }
    // else
    if (m_isCopying) {
        if (!m_copyItem) {
            // 创建临时复制体
            m_copyItem = createCopy();
            // 显示辅助线
            m_showGuideLines = true;
        }

        // 更新复制体位置
        // qDebug() << "move scene: " << event->scenePos();
        QPointF newPos = event->scenePos() - m_mousePressPos;
        QPointF tmpPos = m_copyItem->mapFromScene(newPos);
        m_copyItem->setPos(tmpPos);

        // 绘制辅助线
        scene()->update(scene()->sceneRect());
    }
    else
    {
        QGraphicsRectItem::mouseMoveEvent(event);

        QPointF newPos = pos();

        m_lastPos = newPos;
    }
}

void T_CustomRectItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    return;

    QGraphicsRectItem::mouseReleaseEvent(event);
    //qDebug() << "release: " << event->buttons();
    if(event->button() != Qt::LeftButton) {
        return;
    }
    m_is_tip = true;
    
    m_resizing = false;
    m_resizeDirection = None;

    // 新增复制逻辑
    if(m_isCopying && (event->button() == Qt::LeftButton) && (m_item_data.type == Module)) {
        if (m_copyItem) {
            // 确保复制体在场景中
            if (!scene()->items().contains(m_copyItem)) {
                scene()->addItem(m_copyItem);
            }
            m_copyItem = nullptr; // 清理临时复制体
        }
    }
    // 隐藏辅助线
    m_showGuideLines = false;
    m_isCopying = false;

    updateLayout();

    if(m_item_data.type == Main) {
        //通知模块组更新布局
        emit flushBlockLayout();
    } else if(m_item_data.type == Module || m_item_data.type == Outer) {
        //通知主体模块更新布局
        emit flushMainLayout();
    } else if(m_item_data.type == Block) {
        //通知模块组更新布局
        emit flushSignalBlockLayout();
    }
}

void T_CustomRectItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    return;

    const qreal handleSize = 8;
    QRectF rect = this->rect();
    QPointF pos = event->pos();

    if (qAbs(pos.x() - rect.left()) < handleSize && qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = TopLeft;
    } else if (qAbs(pos.x() - rect.right()) < handleSize && qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = TopRight;
    } else if (qAbs(pos.x() - rect.left()) < handleSize && qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = BottomLeft;
    } else if (qAbs(pos.x() - rect.right()) < handleSize && qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = BottomRight;
    } else if (qAbs(pos.x() - rect.left()) < handleSize) {
        m_resizeDirection = Left;
    } else if (qAbs(pos.x() - rect.right()) < handleSize) {
        m_resizeDirection = Right;
    } else if (qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = Top;
    } else if (qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = Bottom;
    } else if (rect.contains(pos.x(),pos.y())) {
        m_resizeDirection = Inner;
    }else {
        m_resizeDirection = None;
    }

    setCursorShape();
    QGraphicsRectItem::hoverMoveEvent(event);
}

void T_CustomRectItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    return;

    if(m_item_data.type == Main) {
        QMenu menu;
        QAction *spacingAct = menu.addAction("设置边距");
        QAction *cchildItemAct = menu.addAction("调整子项之间间隔");
        QAction *crectfAct = menu.addAction("改变大小位置");
        QAction *addOuterRectAct = menu.addAction("添加外部矩形");
        QAction *deleteAct = menu.addAction("删除");

        QAction *selected = menu.exec(event->screenPos());
        if(selected == spacingAct){
            MarsSpaceIns->SetCurrentData(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
            int ret = MarsSpaceIns->exec();
            if(ret) {
                MarsSpaceIns->ChangeCurrentData(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
                setMarSpacing(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
            }
        } else if(selected == cchildItemAct) {
            cchildItemSpace();
         } else if(selected == deleteAct) {
            emit deleteMainItem();
        } else if(selected == crectfAct) {
            CRectAndPosIns->SetCurrentData(rect());
            int ret = CRectAndPosIns->exec();
            if(ret) {
                QRectF tmprect = rect();
                CRectAndPosIns->ChangeCurrentData(tmprect);
                setNewRectF(tmprect);
            }
        } else if(selected == addOuterRectAct) {
            addOuterRect();
        }
    } else if(m_item_data.type == Outer) {
        QMenu menu;
        QAction *spacingAct = menu.addAction("设置边距");
        QAction *cchildItemAct = menu.addAction("调整子项之间间隔");
        QAction *deleteAct = menu.addAction("删除");

        QAction *selected = menu.exec(event->screenPos());
        if(selected == spacingAct){
            MarsSpaceIns->SetCurrentData(m_mar_spacing_left_outer,m_mar_spacing_top_outer,m_mar_spacing_right_outer,m_mar_spacing_bottom_outer);
            int ret = MarsSpaceIns->exec();
            if(ret) {
                MarsSpaceIns->ChangeCurrentData(m_mar_spacing_left_outer,m_mar_spacing_top_outer,m_mar_spacing_right_outer,m_mar_spacing_bottom_outer);
                setMarSpacing(m_mar_spacing_left_outer,m_mar_spacing_top_outer,m_mar_spacing_right_outer,m_mar_spacing_bottom_outer);
            }
        } else if(selected == cchildItemAct) {
            cchildItemSpace();
         } else if(selected == deleteAct) {
            deleteItems();
        }
    } else if(m_item_data.type == Module) {
        QMenu menu;
        QAction *deleteAct = menu.addAction("删除");
        QAction *crectfAct = menu.addAction("改变大小位置");

        QAction *selected = menu.exec(event->screenPos());
        if(selected == deleteAct) {
            deleteItems();
        } else if(selected == crectfAct) {
            CRectAndPosIns->SetCurrentData(rect());
            int ret = CRectAndPosIns->exec();
            if(ret) {
                QRectF tmprect = rect();
                CRectAndPosIns->ChangeCurrentData(tmprect);
                setNewRectF(tmprect);
            }
        }
    }
}

void T_CustomRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();

    painter->setBrush(brush());
    painter->setPen(pen());
    painter->drawRect(rect());

    // //绘制文本
    // painter->setPen(Qt::black);
    // QStringList tmp_list = m_item_data.name.split("_");
    // if(tmp_list.size() >= 2)
    //     painter->drawText(rect().center(),tmp_list[1]);

    painter->restore();

    // //绘制复制辅助线
    // if (m_showGuideLines && m_copyItem) {
    //     drawGuideLines(painter);
    // }

    //绘制文本
    if(m_item_data.type == Main && m_is_text) {
        //绘制
        drawText(painter);
    }

    //绘制数据标注线
    if(m_item_data.type == Outer && g_is_tip_line && m_is_tip) {
        drawTipLines(painter);
    }
}

T_CustomRectItem *T_CustomRectItem::createCopy() const
{
    T_CustomRectItem* copy = nullptr;
    if(m_item_data.type == Main) {
        return nullptr;
    } else if(m_item_data.type == Module) {
        T_CustomRectItem* m_main_rect = static_cast<T_CustomRectItem*>(this->parentItem());
        copy = new T_CustomRectItem();

        connect(copy,&T_CustomRectItem::flushMainLayout,m_main_rect,&T_CustomRectItem::updateLayout);

        // 复制基本属性
        copy->SetItemInfo(m_item_data);
        QPointF tmp_pos = copy->mapFromScene(m_mousePressPos);
        copy->setRect(tmp_pos.x(),tmp_pos.y(), rect().width(), rect().height());
        copy->setPen(pen());
        copy->setBrush(brush());

        m_main_rect->addChild(copy);
    } else if(m_item_data.type == Block) {
        T_ModuleGroupRectItem* m_group_rect = static_cast<T_ModuleGroupRectItem*>(this->parentItem());
        copy = new T_CustomRectItem();
        connect(copy,&T_CustomRectItem::flushSignalBlockLayout,m_group_rect,&T_ModuleGroupRectItem::updateLayout);
        // 复制基本属性
        copy->SetItemInfo(m_item_data);
        QPointF tmp_pos = copy->mapFromScene(m_mousePressPos);
        copy->setRect(tmp_pos.x(),tmp_pos.y(), rect().width(), rect().height());
        copy->setPen(pen());
        copy->setBrush(brush());
        m_group_rect->addRectangle(copy);
    }
    
    return copy;
}

void T_CustomRectItem::setCursorShape()
{
    switch (m_resizeDirection) {
    case TopLeft:
    case BottomRight:
        setCursor(Qt::SizeFDiagCursor);
        break;
    case TopRight:
    case BottomLeft:
        setCursor(Qt::SizeBDiagCursor);
        break;
    case Left:
    case Right:
        setCursor(Qt::SizeHorCursor);
        break;
    case Top:
    case Bottom:
        setCursor(Qt::SizeVerCursor);
        break;
    case Inner:
        setCursor(Qt::CrossCursor);
        break;
    default:
        setCursor(Qt::ArrowCursor);
        break;
    }
}

void T_CustomRectItem::updateLayout()
{
    prepareGeometryChange();

    calculateGroupSize();

    scene()->update(scene()->sceneRect()); // 更新整个场景
}

QString T_CustomRectItem::getItemName()
{
    return m_item_data.name;
}

cutomitem T_CustomRectItem::getItemData()
{
    return m_item_data;
}

qreal T_CustomRectItem::getMars(LayoutDirectionHV direction)
{
   switch (direction)
    {
    case Left_Top:
        return m_mar_spacing_top;
    case Left_Bottom:
        return m_mar_spacing_left;
    case Right_Top:
        return m_mar_spacing_right;
    case Right_Bottom:
        return m_mar_spacing_bottom;

    default:
        return qreal();;
    }
        
}

qreal T_CustomRectItem::getOuterMars(LayoutDirectionHV direction)
{   
    switch (direction)
    {
    case Left_Top:
        return m_mar_spacing_top_outer;
    case Left_Bottom:
        return m_mar_spacing_left_outer;
    case Right_Top:
        return m_mar_spacing_right_outer;
    case Right_Bottom:
        return m_mar_spacing_bottom_outer;
    
    default:
        return qreal();;
    }
}

void T_CustomRectItem::setMars(qreal left,qreal top,qreal right,qreal bottom)
{
    if(m_item_data.type == Outer) {
        m_mar_spacing_left_outer = left;
        m_mar_spacing_top_outer = top;
        m_mar_spacing_right_outer = right; 
        m_mar_spacing_bottom_outer = bottom;
    } else {
        m_mar_spacing_left = left;
        m_mar_spacing_top = top;
        m_mar_spacing_right = right; 
        m_mar_spacing_bottom = bottom;
    }
    updateLayout();
}

void T_CustomRectItem::calculateGroupSize()
{    
    if (m_children.isEmpty()) {
        return;
    }

    qreal tmp_left_mar;
    qreal tmp_top_mar;
    qreal tmp_right_mar;
    qreal tmp_bottom_mar;
    if(m_item_data.type == Outer) {
        tmp_left_mar = m_mar_spacing_left_outer;
        tmp_top_mar = m_mar_spacing_top_outer;
        tmp_right_mar = m_mar_spacing_right_outer;
        tmp_bottom_mar = m_mar_spacing_bottom_outer;
    } else {
        tmp_left_mar = m_mar_spacing_left;
        tmp_top_mar = m_mar_spacing_top;
        tmp_right_mar = m_mar_spacing_right;
        tmp_bottom_mar = m_mar_spacing_bottom;
    }

    // 获取外部矩形框的大小
    QRectF totalRect = rect();

    // 遍历子项，检查并调整边距
    foreach (QGraphicsRectItem *child, m_children) {
        QRectF itemRect = child->mapRectToParent(child->rect());

        // 计算子项与外部矩形框的边距
        qreal leftMargin = itemRect.left() - totalRect.left();
        qreal topMargin = itemRect.top() - totalRect.top();
        qreal rightMargin = totalRect.right() - itemRect.right();
        qreal bottomMargin = totalRect.bottom() - itemRect.bottom();

        // 检查并调整边距
        QPointF offset(0, 0);

        // 左边距
        if (leftMargin < tmp_left_mar) {
            offset.setX(tmp_left_mar - leftMargin);
        }

        // 上边距
        if (topMargin < tmp_top_mar) {
            offset.setY(tmp_top_mar - topMargin);
        }

        // // 右边距
        // if (rightMargin < tmp_right_mar) {
        //     offset.setX(offset.x() - (tmp_right_mar - rightMargin));
        // }

        // // 下边距
        // if (bottomMargin < tmp_bottom_mar) {
        //     offset.setY(offset.y() - (tmp_bottom_mar - bottomMargin));
        // }

        // 如果需要调整，更新子项的位置
        if (!offset.isNull()) {
            child->setPos(child->pos() + offset);
        }
    }
}

void T_CustomRectItem::setMarSpacing(qreal space_left, qreal space_top, qreal space_right, qreal space_bottom)
{
    if(m_item_data.type == Outer) {
        if(m_mar_spacing_left_outer != space_left || m_mar_spacing_top_outer != space_top || m_mar_spacing_right_outer != space_right || m_mar_spacing_bottom_outer != space_bottom) {
            m_mar_spacing_left_outer = space_left;        
            m_mar_spacing_top_outer = space_top;
            m_mar_spacing_right_outer = space_right;
            m_mar_spacing_bottom_outer = space_bottom;

            updateLayout();
        }
    } else {
        if(m_mar_spacing_left != space_left || m_mar_spacing_top != space_top || m_mar_spacing_right!= space_right || m_mar_spacing_bottom!= space_bottom) {
            m_mar_spacing_left = space_left;        
            m_mar_spacing_top = space_top;
            m_mar_spacing_right = space_right;
            m_mar_spacing_bottom = space_bottom;

            updateLayout();
        }
    }
}

void T_CustomRectItem::setNewRectF(const QRectF &rectf)
{
    calaOldRects();
    calcZoomRects(rectf);
    updateLayout();

    if(m_item_data.type == Main) {
        //通知模块组更新布局
        emit flushBlockLayout();
    } else if(m_item_data.type == Module || m_item_data.type == Outer) {
        //通知主体模块更新布局
        emit flushMainLayout();
    }
}

void T_CustomRectItem::cchildItemSpace()
{
    m_oldRects.clear();
    //TODO：添加子项间距代码模块
    m_elaWidget = new ElaWidget;
    m_elaWidget->setWindowButtonFlag(ElaAppBarType::CloseButtonHint,false);
    m_elaWidget->setWindowButtonFlag(ElaAppBarType::MinimizeButtonHint,false);
    m_elaWidget->setWindowButtonFlag(ElaAppBarType::MaximizeButtonHint,false);
    m_elaWidget->setWindowButtonFlag(ElaAppBarType::StayTopButtonHint,false);
    m_elaWidget->setWindowTitle("调整子项间距");

    ElaMultiSelectComboBox* multiSelectComboBox = new ElaMultiSelectComboBox(m_elaWidget);
    QStringList multiComboList;
    multiComboList.clear();

    QStringList multiSelectComboList;
    multiSelectComboList.clear();
    
    for (auto child : m_children) {
        T_CustomRectItem* customItem = dynamic_cast<T_CustomRectItem*>(child);
        if (customItem) {
            // 如果转换成功，说明child是T_CustomRectItem类型
            QString tmpname = customItem->getItemName();
            multiComboList.append(tmpname);
            m_oldRects[tmpname] = customItem;
        } else {
            // 如果转换失败，尝试将child动态转换为T_ModuleGroupRectItem类型
            T_ModuleGroupRectItem* groupItem = dynamic_cast<T_ModuleGroupRectItem*>(child);
            if (groupItem) {
                // 如果转换成功，说明child是T_ModuleGroupRectItem类型
                QString tmpname = groupItem->getItemName();
                multiComboList.append(tmpname);
                m_oldRects[tmpname] = groupItem;
            } else {
                // 如果转换失败，说明child既不是T_CustomRectItem也不是T_ModuleGroupRectItem类型
                qDebug() << "child is not a T_CustomRectItem or T_ModuleGroupRectItem";
            }
        }
    }

    multiSelectComboBox->addItems(multiComboList);
    multiSelectComboBox->setCurrentSelection(multiSelectComboList);

    ElaText* text = new ElaText(m_elaWidget);
    text->setText("请选择两项子项调整间隔：");
    text->setTextPixelSize(14);    

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(text);
    hLayout->addSpacing(10);
    hLayout->addWidget(multiSelectComboBox);

    ElaText *text1 = new ElaText(m_elaWidget);
    text1->setText("当前选中的子项水平间隔：");
    text1->setTextPixelSize(14);

    ElaLineEdit *lineEdit = new ElaLineEdit(m_elaWidget);
    lineEdit->setText("0");

    ElaComboBox *comboBox = new ElaComboBox(m_elaWidget);
    comboBox->setObjectName("comboBox");
    comboBox->addItem("左侧对齐");
    comboBox->addItem("右侧对齐");
    comboBox->setCurrentIndex(1);

    QHBoxLayout *hLayout1 = new QHBoxLayout;
    hLayout1->addWidget(text1);
    hLayout1->addSpacing(10);
    hLayout1->addWidget(lineEdit);
    hLayout1->addSpacing(10);
    hLayout1->addWidget(comboBox);

    ElaText *text2 = new ElaText(m_elaWidget);
    text2->setText("当前选中的子项垂直间隔：");
    text2->setTextPixelSize(14);

    ElaLineEdit *lineEdit1 = new ElaLineEdit(m_elaWidget);
    lineEdit1->setText("0");

    ElaComboBox *comboBox1 = new ElaComboBox(m_elaWidget);
    comboBox1->setObjectName("comboBox1");
    comboBox1->addItem("顶部对齐");
    comboBox1->addItem("底部对齐");
    comboBox1->setCurrentIndex(0);    

    QHBoxLayout *hLayout2 = new QHBoxLayout;
    hLayout2->addWidget(text2);
    hLayout2->addSpacing(10);
    hLayout2->addWidget(lineEdit1);
    hLayout2->addSpacing(10);
    hLayout2->addWidget(comboBox1);

    ElaPushButton *okButton = new ElaPushButton(m_elaWidget);
    connect(okButton,&ElaPushButton::clicked,[=](){
        QStringList tmpList = multiSelectComboBox->getCurrentSelection();
        if(tmpList.size() != 2) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请选择两项子项调整间隔！",3000,m_elaWidget);
            return;
        }

        QString tmpstr = lineEdit->text();
        if(tmpstr.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入子项水平间隔！",3000,m_elaWidget);
            return;
        }

        QString tmpstr1 = lineEdit1->text();
        if(tmpstr1.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入子项垂直间隔！",3000,m_elaWidget);
            return;
        }

        onOkElaWidget(tmpList,tmpstr.toDouble(),tmpstr1.toDouble(),comboBox->currentText(),comboBox1->currentText());
    });
    okButton->setText("确定");

    ElaPushButton *cancelButton = new ElaPushButton(m_elaWidget);
    connect(cancelButton,&ElaPushButton::clicked,this,&T_CustomRectItem::closeElaWidget);
    cancelButton->setText("取消");

    QHBoxLayout *hLayout3 = new QHBoxLayout;
    hLayout3->addWidget(okButton);
    hLayout3->addSpacing(10);
    hLayout3->addWidget(cancelButton);

    QVBoxLayout *vLayout = new QVBoxLayout(m_elaWidget);
    vLayout->addLayout(hLayout);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout2);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout3);

    m_elaWidget->moveToCenter();
    m_elaWidget->show();
}

void T_CustomRectItem::deleteItems()
{
    T_CustomRectItem* m_main_rect = static_cast<T_CustomRectItem*>(this->parentItem());
    T_CustomRectItem *rect = this;
    disconnect(rect,&T_CustomRectItem::flushMainLayout,m_main_rect,&T_CustomRectItem::updateLayout);

    m_main_rect->removeChild(rect);
    scene()->removeItem(rect);
    delete rect;
    rect = nullptr;
}

void T_CustomRectItem::cchildItemSpaceSignal(const QStringList &list, double hSpace, double vSpace, const QString &hLayout, const QString &vLayout)
{
    m_oldRects.clear();

    for (auto child : m_children) {
        T_CustomRectItem* customItem = dynamic_cast<T_CustomRectItem*>(child);
        if (customItem) {
            // 如果转换成功，说明child是T_CustomRectItem类型
            QString tmpname = customItem->getItemName();
            m_oldRects[tmpname] = customItem;
        } else {
            // 如果转换失败，尝试将child动态转换为T_ModuleGroupRectItem类型
            T_ModuleGroupRectItem* groupItem = dynamic_cast<T_ModuleGroupRectItem*>(child);
            if (groupItem) {
                // 如果转换成功，说明child是T_ModuleGroupRectItem类型
                QString tmpname = groupItem->getItemName();
                m_oldRects[tmpname] = groupItem;
            } else {
                // 如果转换失败，说明child既不是T_CustomRectItem也不是T_ModuleGroupRectItem类型
                qDebug() << "child is not a T_CustomRectItem or T_ModuleGroupRectItem";
            }
        }
    }

    if(list.size() != 2) {
        ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "子项数量错误",3000,m_elaWidget);
        return;
    }
    onOkElaWidget(list,hSpace,vSpace,hLayout,vLayout);
}

void T_CustomRectItem::calaOldRects()
{
    m_originalContainerRect = this->rect();
    m_originalChildPositions.clear();
    m_originalChildRects.clear();
    for (auto child : m_children) {
        m_originalChildPositions[child] = child->pos();
        m_originalChildRects[child] = child->rect();
    }

    m_isFirstResize = false;
}

void T_CustomRectItem::calcZoomRects(const QRectF &newRect)
{
    // 确保矩形大小不为负
    if (newRect.width() > 0 && newRect.height() > 0)
    {
        setRect(newRect);

        //新增
        // 计算缩放比例
        const qreal scaleX = newRect.width() / m_originalContainerRect.width();
        const qreal scaleY = newRect.height() / m_originalContainerRect.height();

        // 缩放子项
        for (auto child : m_children) {
            const QPointF newPos(
                m_originalChildPositions[child].x() * scaleX,
                m_originalChildPositions[child].y() * scaleY
            );
            const QRectF newChildRect(
                0, 0,
                m_originalChildRects[child].width() * scaleX,
                m_originalChildRects[child].height() * scaleY
            );
            child->setPos(newPos);
            child->setRect(newChildRect);
        }
    }
}

void T_CustomRectItem::drawGuideLines(QPainter *painter)
{
    painter->save();
    // 绘制辅助线
    QPen guidePen(Qt::DashLine);
    guidePen.setColor(Qt::green);
    guidePen.setWidth(1);
    painter->setPen(guidePen);

    // 绘制水平和垂直辅助线
    int yp = boundingRect().top();
    int yb = boundingRect().bottom();
    int xp = boundingRect().left();
    int xb = boundingRect().right();

    painter->drawLine(xb, yp, xb + GuideLineNum, yp); 
    painter->drawLine(xp, yp, xb - GuideLineNum, yp); 
    painter->drawLine(xb, yb, xb + GuideLineNum, yb);
    painter->drawLine(xp, yb, xb - GuideLineNum, yb);
    painter->drawLine(xp, yp, xp, yp - GuideLineNum);
    painter->drawLine(xp, yb, xp, yb + GuideLineNum);
    painter->drawLine(xb, yp, xb, yp - GuideLineNum);
    painter->drawLine(xb, yb, xb, yb + GuideLineNum);

    painter->restore();
}

void T_CustomRectItem::drawTipLines(QPainter *painter)
{
    painter->save();
    //绘制线条标注
    painter->setPen(Qt::red);    
    painter->setFont(QFont("Arial", 20)); // 固定大小
    //绘制水平线
    int rect_center_x = (rect().topLeft().x() + rect().topRight().x())/2;
    int rect_center_y = rect().top();
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y() - 5,
                        rect_center_x - 20,rect_center_y - 5);
    painter->drawLine(rect_center_x + 20,rect_center_y - 5,
                        rect().topRight().x(),rect().topRight().y() - 5);
    //绘制竖直线条
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y(),rect().topLeft().x(),rect().topLeft().y() - 10);
    painter->drawLine(rect().topRight().x(),rect().topRight().y(),rect().topRight().x(),rect().topRight().y() - 10);
    //中间绘制宽度
    painter->drawText(rect_center_x - 10,rect_center_y-7,QString::number(rect().width(),'f',2));

    //绘制垂直线条
    int center_y_x = rect().left();
    int center_y_y = (rect().topLeft().y() + rect().bottomLeft().y()) / 2;;
    painter->drawLine(rect().topLeft().x() - 5,rect().topLeft().y(),center_y_x - 5,center_y_y - 20);
    painter->drawLine(center_y_x - 5,center_y_y + 20,rect().bottomLeft().x() - 5,rect().bottomLeft().y());
    //绘制水平小线条
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y(),rect().topLeft().x()-10,rect().topLeft().y());
    painter->drawLine(rect().bottomLeft().x(),rect().bottomLeft().y(),rect().bottomLeft().x()-10,rect().bottomLeft().y());

    //计算文本中心点
    QRect textRect = painter->fontMetrics().boundingRect(center_y_x, center_y_y, 10, 10, Qt::AlignCenter, QString::number(rect().height(), 'f', 1));
    QPoint textCenter = QPoint(textRect.center().x(), textRect.center().y());
    // 以文本的中心为旋转中心
    painter->translate(textCenter.x(), textCenter.y());
    painter->rotate(-90);
    painter->translate(-textCenter.x(), -textCenter.y());
    painter->drawText(textCenter.x()-10, textCenter.y()-8,QString::number(rect().height(),'f',2));

    painter->restore();
}

void T_CustomRectItem::drawText(QPainter *painter)
{
    painter->save();
    QPen pen;
    pen.setColor(Qt::red);
    pen.setWidth(5);
    painter->setPen(pen);
    painter->setFont(QFont("Arial", 28)); // 固定大小

    int rect_center_x = rect().left() + rect().width() / 2;
    int rect_center_y = rect().top() + (MAINTOP / 2);
    painter->drawText(rect_center_x,rect_center_y,"装配边界");

    rect_center_y = rect().bottom() - (MAINBOTTOM / 2);
    painter->drawText(rect_center_x,rect_center_y,"装配边界");

    rect_center_x = rect().right() - (MAINRIGHT / 2);
    rect_center_y = rect().top() + (rect().height() / 2);
    painter->drawText(rect_center_x,rect_center_y,"高\n压\n模\n块");

    painter->restore();
}

void T_CustomRectItem::closeElaWidget()
{
    if(m_elaWidget == nullptr) {
        return;
    }
    m_elaWidget->close();
    delete m_elaWidget;
    m_elaWidget = nullptr;
}

void T_CustomRectItem::closeElaWidget2()
{
    if(m_elaWidget2 == nullptr) {
        return;
    }
    m_elaWidget2->close();
    delete m_elaWidget2;
    m_elaWidget2 = nullptr;
}

void T_CustomRectItem::onOkElaWidget(QStringList list,qreal hspacing,qreal vspacing,const QString &hLayout,const QString &vLayout)
{
    if (list.size() < 2) {
        qDebug() << "List size is less than 2, cannot process two rectangles.";
        return;
    }

    QString firstRectName = list[0];
    QString secondRectName = list[1];

    if (!m_oldRects.contains(firstRectName) || !m_oldRects.contains(secondRectName)) {
        qDebug() << "One or both of the rectangle names are not found in m_oldRects.";
        return;
    }

    //获取对齐方式
    setLayoutDirect(hLayout,vLayout);

    // 获取第一个项
    T_CustomRectItem* firstCustomItem = dynamic_cast<T_CustomRectItem*>(m_oldRects[firstRectName]);
    T_ModuleGroupRectItem* firstGroupItem = dynamic_cast<T_ModuleGroupRectItem*>(m_oldRects[firstRectName]);

    // 检查第一个项是否有效
    if (!firstCustomItem && !firstGroupItem) {
        qWarning() << "No valid first item found.";
        return;
    }

    // 获取第二个项
    T_CustomRectItem* secondCustomItem = dynamic_cast<T_CustomRectItem*>(m_oldRects[secondRectName]);
    T_ModuleGroupRectItem* secondGroupItem = dynamic_cast<T_ModuleGroupRectItem*>(m_oldRects[secondRectName]);

    // 检查第二个项是否有效
    if (!secondCustomItem && !secondGroupItem) {
        qWarning() << "No valid second item found.";
        return;
    }

    QRectF first_tmp_rect;
    QRectF second_tmp_rect;

    // 确定第一个项的矩形
    if (firstCustomItem) {        
        first_tmp_rect = firstCustomItem->mapRectToParent(firstCustomItem->rect());
    } else if (firstGroupItem) {
        first_tmp_rect = firstGroupItem->mapRectToParent(firstGroupItem->rect());
    }

    // 确定第二个项的矩形
    if (secondCustomItem) {
        second_tmp_rect = secondCustomItem->mapRectToParent(secondCustomItem->rect());
    } else if (secondGroupItem) {
        second_tmp_rect = secondGroupItem->mapRectToParent(secondGroupItem->rect());
    }
    
    // 获取外部矩形框的大小
    QRectF totalRect = rect();
    // 计算子项1与外部矩形框的边距
    qreal leftMargin_first = first_tmp_rect.left() - totalRect.left();
    qreal topMargin_first = first_tmp_rect.top() - totalRect.top();
    qreal rightMargin_first = totalRect.right() - first_tmp_rect.right();
    qreal bottomMargin_first = totalRect.bottom() - first_tmp_rect.bottom();
    // 计算子项2与外部矩形框的边距
    qreal leftMargin_second = second_tmp_rect.left() - totalRect.left();
    qreal topMargin_second = second_tmp_rect.top() - totalRect.top();
    qreal rightMargin_second = totalRect.right() - second_tmp_rect.right();
    qreal bottomMargin_second = totalRect.bottom() - second_tmp_rect.bottom();    

    // 根据布局方向设置位置
    if (m_layoutDirection == Left_Top) {
        setPositionBasedOnDirection(
            leftMargin_second - leftMargin_first,
            topMargin_second - topMargin_first,
            secondCustomItem,
            secondGroupItem,
            hspacing,
            vspacing
        );
    } else if (m_layoutDirection == Left_Bottom) {
        setPositionBasedOnDirection(
            leftMargin_second - leftMargin_first,
            topMargin_second - topMargin_first - first_tmp_rect.height(),
            secondCustomItem,
            secondGroupItem,
            hspacing,
            vspacing   
        );
    } else if (m_layoutDirection == Right_Top) {
        setPositionBasedOnDirection(
            leftMargin_second - leftMargin_first - first_tmp_rect.width(),
            topMargin_second - topMargin_first,
            secondCustomItem, 
            secondGroupItem,
            hspacing,
            vspacing 
        );
    } else if (m_layoutDirection == Right_Bottom) {
        setPositionBasedOnDirection(
            leftMargin_second - leftMargin_first - first_tmp_rect.width(),
            topMargin_second - topMargin_first - first_tmp_rect.height(),
            secondCustomItem, 
            secondGroupItem,
            hspacing,
            vspacing 
        );
    }

    //更新布局
    updateLayout();

    // 如果需要，可以在这里更新UI或其他相关操作
    closeElaWidget();
}

void T_CustomRectItem::setLayoutDirect(const QString &str, const QString &str2)
{
    if(str.compare("左侧对齐") == 0 && str2.compare("顶部对齐") == 0) {
        m_layoutDirection = Left_Top;
    } else if(str.compare("左侧对齐") == 0 && str2.compare("底部对齐") == 0) {
        m_layoutDirection = Left_Bottom; 
    } else if(str.compare("右侧对齐") == 0 && str2.compare("顶部对齐") == 0) {
        m_layoutDirection = Right_Top; 
    } else if(str.compare("右侧对齐") == 0 && str2.compare("底部对齐") == 0) {
        m_layoutDirection = Right_Bottom; 
    }
}

void T_CustomRectItem::setPositionBasedOnDirection(qreal diff_h, qreal diff_v,T_CustomRectItem *item,T_ModuleGroupRectItem *groupItem,qreal hspacing,qreal vspacing)
{
    QPointF offset(0, 0);
    offset.setX(diff_h - hspacing);
    offset.setY(diff_v - vspacing);
    if(item) {
        item->setPos(item->pos() - offset); 
    } else if(groupItem) {
        groupItem->setPos(groupItem->pos() - offset); 
    }
}

void T_CustomRectItem::addOuterRect()
{
    m_addRects.clear();
    //为选择的矩形添加外框
    m_elaWidget2 = new ElaWidget;
    m_elaWidget2->setWindowButtonFlag(ElaAppBarType::CloseButtonHint,false);
    m_elaWidget2->setWindowButtonFlag(ElaAppBarType::MinimizeButtonHint,false);
    m_elaWidget2->setWindowButtonFlag(ElaAppBarType::MaximizeButtonHint,false);
    m_elaWidget2->setWindowButtonFlag(ElaAppBarType::StayTopButtonHint,false);
    m_elaWidget2->setWindowTitle("为选择的矩形创建外框");

    ElaMultiSelectComboBox* multiSelectComboBox = new ElaMultiSelectComboBox(m_elaWidget2);
    QStringList multiComboList;
    multiComboList.clear();

    QStringList multiSelectComboList;
    multiSelectComboList.clear();
    
    for (auto child : m_children) {
        T_CustomRectItem* customItem = dynamic_cast<T_CustomRectItem*>(child);
        if (customItem) {
            // 如果转换成功，说明child是T_CustomRectItem类型
            QString tmpname = customItem->getItemName();
            multiComboList.append(tmpname);
            m_addRects[tmpname] = customItem;
        } else {
            // 如果转换失败，尝试将child动态转换为T_ModuleGroupRectItem类型
            T_ModuleGroupRectItem* groupItem = dynamic_cast<T_ModuleGroupRectItem*>(child);
            if (groupItem) {
                // 如果转换成功，说明child是T_ModuleGroupRectItem类型
                QString tmpname = groupItem->getItemName();
                multiComboList.append(tmpname);
                m_addRects[tmpname] = groupItem;
            } else {
                // 如果转换失败，说明child既不是T_CustomRectItem也不是T_ModuleGroupRectItem类型
                qDebug() << "child is not a T_CustomRectItem or T_ModuleGroupRectItem";
            }
        }
    }

    multiSelectComboBox->addItems(multiComboList);
    multiSelectComboBox->setCurrentSelection(multiSelectComboList);

    ElaText* text = new ElaText(m_elaWidget2);
    text->setText("选择的子项：");
    text->setTextPixelSize(14);  

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(text);
    hLayout->addSpacing(10);
    hLayout->addWidget(multiSelectComboBox);

    ElaText* text1 = new ElaText(m_elaWidget2);
    text1->setText("上边距：");
    text1->setTextPixelSize(14);   

    ElaLineEdit *lineEdit1 = new ElaLineEdit(m_elaWidget2);
    lineEdit1->setText(QString::number(m_mar_spacing_top_outer,'f',2));

    QHBoxLayout *hLayout1 = new QHBoxLayout;
    hLayout1->addWidget(text1);
    hLayout1->addSpacing(10);
    hLayout1->addWidget(lineEdit1);
    
    ElaText* text2 = new ElaText(m_elaWidget2);
    text2->setText("下边距：");
    text2->setTextPixelSize(14);
    ElaLineEdit *lineEdit2 = new ElaLineEdit(m_elaWidget2);
    lineEdit2->setText(QString::number(m_mar_spacing_bottom_outer,'f',2));

    QHBoxLayout *hLayout2 = new QHBoxLayout;
    hLayout2->addWidget(text2);
    hLayout2->addSpacing(10);
    hLayout2->addWidget(lineEdit2);

    ElaText* text3 = new ElaText(m_elaWidget2);
    text3->setText("左边距：");
    text3->setTextPixelSize(14);
    ElaLineEdit *lineEdit3 = new ElaLineEdit(m_elaWidget2);
    lineEdit3->setText(QString::number(m_mar_spacing_left_outer,'f',2));

    QHBoxLayout *hLayout3 = new QHBoxLayout;
    hLayout3->addWidget(text3);
    hLayout3->addSpacing(10);
    hLayout3->addWidget(lineEdit3);

    ElaText* text4 = new ElaText(m_elaWidget2);
    text4->setText("右边距：");
    text4->setTextPixelSize(14);
    ElaLineEdit *lineEdit4 = new ElaLineEdit(m_elaWidget2);
    lineEdit4->setText(QString::number(m_mar_spacing_right_outer,'f',2));

    QHBoxLayout *hLayout4 = new QHBoxLayout;
    hLayout4->addWidget(text4);
    hLayout4->addSpacing(10);
    hLayout4->addWidget(lineEdit4);

    ElaPushButton *okButton = new ElaPushButton(m_elaWidget2);
    connect(okButton,&ElaPushButton::clicked,[=](){
        QStringList tmpList = multiSelectComboBox->getCurrentSelection();
        QString tmpstr = lineEdit1->text();
        if(tmpstr.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入上边距！",3000,m_elaWidget);
            return;
        }

        QString tmpstr1 = lineEdit2->text();
        if(tmpstr1.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入下边距！",3000,m_elaWidget);
            return;
        }

        QString tmpstr2 = lineEdit3->text();
        if(tmpstr2.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入左边距！",3000,m_elaWidget);
            return;
        }

        QString tmpstr3 = lineEdit4->text();
        if(tmpstr3.isEmpty()) {
            ElaMessageBar::warning(ElaMessageBarType::BottomRight, "警告", "请输入右边距！",3000,m_elaWidget);
            return;
        }

        onAddOuterRect(tmpList,tmpstr.toDouble(),tmpstr1.toDouble(),tmpstr2.toDouble(),tmpstr3.toDouble());   
    });   
    okButton->setText("确定");

    ElaPushButton *cancelButton = new ElaPushButton(m_elaWidget2);
    connect(cancelButton,&ElaPushButton::clicked,this,&T_CustomRectItem::closeElaWidget2);
    cancelButton->setText("取消");

    QHBoxLayout *hLayout5 = new QHBoxLayout;
    hLayout5->addWidget(okButton);
    hLayout5->addSpacing(10);
    hLayout5->addWidget(cancelButton);

    QVBoxLayout *vLayout = new QVBoxLayout(m_elaWidget2);
    vLayout->addLayout(hLayout);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout2);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout3);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout4);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout5);

    m_elaWidget2->moveToCenter();
    m_elaWidget2->show();
}

void T_CustomRectItem::addOuterRect_paintLine(const QStringList &tmpList)
{
    m_addRects.clear();

    for (auto child : m_children) {
        T_CustomRectItem* customItem = dynamic_cast<T_CustomRectItem*>(child);
        if (customItem) {
            // 如果转换成功，说明child是T_CustomRectItem类型
            QString tmpname = customItem->getItemName();
            m_addRects[tmpname] = customItem;
        } else {
            // 如果转换失败，尝试将child动态转换为T_ModuleGroupRectItem类型
            T_ModuleGroupRectItem* groupItem = dynamic_cast<T_ModuleGroupRectItem*>(child);
            if (groupItem) {
                // 如果转换成功，说明child是T_ModuleGroupRectItem类型
                QString tmpname = groupItem->getItemName();
                m_addRects[tmpname] = groupItem;
            } else {
                // 如果转换失败，说明child既不是T_CustomRectItem也不是T_ModuleGroupRectItem类型
                qDebug() << "child is not a T_CustomRectItem or T_ModuleGroupRectItem";
            }
        }
    }

    onAddOuterRect(tmpList,0.0,0.0,0.0,0.0);
}

void T_CustomRectItem::setIsText(bool isText)
{
    m_is_text = isText;
}

void T_CustomRectItem::onAddOuterRect(QStringList list, qreal topMar, qreal bottomMar, qreal leftMar, qreal rightMar)
{
    //qDebug() << "onAddOuterRect" << list << topMar << bottomMar << leftMar << rightMar;
    //添加外框
    T_CustomRectItem *item = new T_CustomRectItem;
    connect(item,&T_CustomRectItem::flushMainLayout,this,&T_CustomRectItem::updateLayout);
    
    QRectF totalRect;
    for (auto key : m_addRects.keys()) {
        if(!list.contains(key)) {
            continue;
        }
        QRectF itemRect = m_addRects[key]->mapRectToParent(m_addRects[key]->rect());
        totalRect = totalRect.united(itemRect);
        removeChild(m_addRects[key]);
        item->addChild(m_addRects[key]);        

        //重新绑定信号槽
        T_CustomRectItem* customItem = dynamic_cast<T_CustomRectItem*>(m_addRects[key]);
        T_ModuleGroupRectItem* groupItem = dynamic_cast<T_ModuleGroupRectItem*>(m_addRects[key]);
        if(customItem) {
            disconnect(customItem,&T_CustomRectItem::flushMainLayout,this,&T_CustomRectItem::updateLayout);
            connect(customItem,&T_CustomRectItem::flushMainLayout,item,&T_CustomRectItem::updateLayout); 
        } else if(groupItem) {
            disconnect(groupItem,&T_ModuleGroupRectItem::flushMainRect,this,&T_CustomRectItem::updateLayout);
            connect(groupItem,&T_ModuleGroupRectItem::flushMainRect,item,&T_CustomRectItem::updateLayout);     
            disconnect(this, &T_CustomRectItem::flushBlockLayout, groupItem, &T_ModuleGroupRectItem::updateLayout);    
            connect(item, &T_CustomRectItem::flushBlockLayout, groupItem, &T_ModuleGroupRectItem::updateLayout);  
        }
    }

    // 调整容器矩形
    cutomitem tmp_item;
    tmp_item.name = "外框";
    tmp_item.type = Outer;
    tmp_item.color = /*m_item_data.color*/QColor(175,203,204);
    tmp_item.rect = totalRect.adjusted(-leftMar, -topMar, rightMar, bottomMar);
    QPointF scene_pos = scene()->views().first()->mapToScene(tmp_item.rect.x(),tmp_item.rect.y());
    QPointF item_point = item->mapFromScene(scene_pos.x(),scene_pos.y());
    item->SetItemInfo(tmp_item);  
    this->addChild(item);
    item->setMars(leftMar,topMar,rightMar,bottomMar);

    //更新布局
    updateLayout();

    // 如果需要，可以在这里更新UI或其他相关操作
    closeElaWidget2();
}
